package com.xiaoshuidi.cloud.module.report.service.ajreport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.ajreport.vo.ReportSalesControlExportVO;
import com.xiaoshuidi.cloud.module.report.controller.ajreport.vo.ReportSalesControlReqVO;
import com.xiaoshuidi.cloud.module.report.controller.ajreport.vo.ReportSalesControlRespVO;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.ExportRespVO;
import com.xiaoshuidi.cloud.module.report.convert.ajreport.ReportSalesControlConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportSalesControlDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportSalesControlMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportSalesControlServiceImpl implements ReportSalesControlService{

    private final ReportSalesControlMapper reportSalesControlMapper;
    private final ConfigValues configValues;
    private final OosFileService oosFileService;
    /**
     * 预定台账列表查询
     */
    public PageResult<ReportSalesControlRespVO> salesControlPage(ReportSalesControlReqVO reqVO){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        reqVO.setTenantId(loginUser.getTenantId());
        Page<ReportSalesControlDO> page = new Page<>(reqVO.getPageNo(),reqVO.getPageSize());
        IPage<ReportSalesControlDO> pageQueryList = reportSalesControlMapper.pageList(page, reqVO);

//        Page<ReportSalesControlDO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
//        LambdaQueryWrapper<ReportSalesControlDO> queryWrapper = new LambdaQueryWrapper<>();
//        if (!ObjectUtils.isEmpty(reqVO.getApartmentId())) {
//            queryWrapper.eq(ReportSalesControlDO::getApartmentId, reqVO.getApartmentId());
//        }
//        if (!ObjectUtils.isEmpty(reqVO.getVacantFlag())) {
//            queryWrapper.eq(ReportSalesControlDO::getVacantFlag, reqVO.getVacantFlag());
//        }
//        if (StringUtils.isNotBlank(reqVO.getRoomStatus())) {
//            queryWrapper.eq(ReportSalesControlDO::getRoomStatus, reqVO.getRoomStatus());
//        }
//        if (StringUtils.isNotBlank(reqVO.getArea())) {
//            queryWrapper.like(ReportSalesControlDO::getArea, reqVO.getArea());
//        }
//        if (StringUtils.isNotBlank(reqVO.getToward())) {
//            queryWrapper.eq(ReportSalesControlDO::getToward, reqVO.getToward());
//        }
//        if (StringUtils.isNotBlank(reqVO.getHouseResource())) {
//            queryWrapper.like(ReportSalesControlDO::getHouseResource, reqVO.getHouseResource());
//        }
//        if (!ObjectUtils.isEmpty(reqVO.getVacantDateEnd())&&!ObjectUtils.isEmpty(reqVO.getVacantDateStart())) {
//            queryWrapper.ge(ReportSalesControlDO::getVacantDate, reqVO.getVacantDateStart());
//            queryWrapper.le(ReportSalesControlDO::getVacantDate, reqVO.getVacantDateEnd());
//        }
//
//        queryWrapper.eq(ReportSalesControlDO::getTenantId,loginUser.getTenantId());
//        queryWrapper.eq(ReportSalesControlDO::getHandleFlag,1);
//        queryWrapper.orderByDesc(ReportSalesControlDO::getUpdateTime);
//        page = reportSalesControlMapper.selectPage(page, queryWrapper);
        if(pageQueryList.getTotal()==0){
            return new PageResult<>(0L);
        }
        PageResult<ReportSalesControlDO> pageResult = new PageResult<>(pageQueryList.getRecords(), pageQueryList.getTotal());

        return  ReportSalesControlConvert.INSTANCE.convertPage(pageResult);
    }

    /**
     * 预定台账表导出
     */
    public ExportRespVO salesControlExport(ReportSalesControlReqVO req){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        long count = reportSalesControlMapper.countSalesControlForExport(req);
        if (count <= 0) {
            throw new ServiceException(ErrorCodeConstants.SALES_CONTROL_NOT_EXISTS);
        }
        int pageSize = 2000;
        int totalPage = (int) count / pageSize;
        if (count % pageSize != 0) {
            totalPage++;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String format = sdf.format(new Date());
        String fileName = format + "销控表.xlsx";

        String filePath = configValues.getNfsPath() + File.separator + fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, ReportSalesControlExportVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        for (int i = 1; i <= totalPage; i++) {
            List<ReportSalesControlDO> infoDOList = reportSalesControlMapper.selectSalesControlForExport(req, (i - 1) * pageSize, pageSize);
            List<ReportSalesControlExportVO> list = ReportSalesControlConvert.INSTANCE.convertList(infoDOList);
            excelWriter.write(list, sheet);
        }
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

}
